package com.example.testapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;


/**
 * @author wwq on 2019/7/18  17:28.
 */
public class MenuProject extends Fragment {
    private NetBroadcastReceiver netBroadcastReceiver;
    private LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;
    private TextView tvProject;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.menu_project, container, false);

        tvProject = view.findViewById(R.id.tvShowNetwork);

        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        netBroadcastReceiver = new NetBroadcastReceiver();
        getContext().registerReceiver(netBroadcastReceiver, filter);
        netBroadcastReceiver.onReceive(getActivity(), null);

        IntentFilter filterLocal = new IntentFilter();
        filterLocal.addAction("com.example.LOCAL_BROADCAST");
        localReceiver = new LocalReceiver();
        localBroadcastManager=LocalBroadcastManager.getInstance(getActivity());
        localBroadcastManager.registerReceiver(localReceiver,filterLocal);

        return view;
    }

    public class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context,"接受到本地广播",Toast.LENGTH_SHORT).show();
            tvProject.setText(intent.getStringExtra("str"));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getContext().unregisterReceiver(netBroadcastReceiver);
        localBroadcastManager.unregisterReceiver(localReceiver);
    }

}
